package com.vlong.town.controller.admin.index;

import com.vlong.town.controller.base.BaseController;
import com.vlong.town.entity.base.DataMessage;
import com.vlong.town.entity.menu.Menu;
import com.vlong.town.entity.role.Role;
import com.vlong.town.entity.user.User;
import com.vlong.town.service.menu.MenuService;
import com.vlong.town.service.role.RoleService;
import com.vlong.town.service.user.UserService;
import com.vlong.town.util.common.TownConstant;
import com.vlong.town.util.data.DataUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * 系统主页Controller
 * @author Assassin
 */
@Controller
public class IndexController extends BaseController {

    // Fields

    @Autowired
    private UserService userService;// 用户业务接口
    @Autowired
    private RoleService  roleService;//角色业务接口
    @Autowired
    private MenuService menuService;//菜单业务接口

    /**
     * 跳转主页面
     * @return
     */
    @RequestMapping("/main")
    public  String  main(){
    	return  "admin/common/main";
    }
    
    @ResponseBody
    @RequestMapping("setRoleId")
    public  DataMessage  setRoleId(String roleId){
    	DataMessage dm = new DataMessage();
    	if(roleId==null||roleId.equals("")) {
    		request.getSession().setAttribute("roleId", "null");
    	}else {
    		request.getSession().setAttribute("roleId", roleId);
    	}
    	return  dm;
    }
    
    /**
     * 跳转头部页面
     * @return
     */
    @RequestMapping("/head")
    public  String  toHead(){
    	List<Role> rolelist = this.roleService.queryRoleByUserId(getUserId());
    	request.setAttribute("listSize", rolelist.size());
		request.setAttribute("listRole", rolelist);
		if(request.getSession().getAttribute("roleId")==null) {
			Long userId = getUserId();
			List<Role> roleList = this.roleService.queryRoleByUserId(userId);
			request.getSession().setAttribute("roleId", roleList.get(0).getRoleId());
		}
		request.setAttribute("roleIds", request.getSession().getAttribute("roleId").toString());
    	return  "admin/common/header";
    }
    
    /**
     * 跳转菜单页面
     * @return
     */
    @RequestMapping("/menu")
    public  String  toMenu(){
    	// 查询用户角色信息
    	List<Role> rolelist = this.roleService.queryRoleByUserId(getUserId());
    	Set<Menu> menuSet = new HashSet<Menu>();
		ArrayList<Menu> menus = new ArrayList<Menu>();
		//String roleId = request.getSession().getAttribute("roleId").toString();
		String roleId="";
		if(request.getSession().getAttribute("roleId")==null) {
			Long userId = getUserId();
			List<Role> roleList = this.roleService.queryRoleByUserId(userId);
			request.getSession().setAttribute("roleId",roleList.get(0).getRoleId());
		}
		roleId = request.getSession().getAttribute("roleId").toString();
		//如果权限Id不为空
		if(roleId!=null&&!"".equals(roleId)&&!"null".equals(roleId)) {
			List<Menu> menuList = this.menuService.queryMenuByRoleId(Long.parseLong(roleId));
			for(Menu menu: menuList) {
				menus.add(menu);
			}
		}else {
			for (Role role : rolelist) {
				List<Menu> menuList = this.menuService.queryMenuByRoleId(role.getRoleId());
				for(Menu menu: menuList) {
					menuSet.add(menu);
				}
			}
			// 构建菜单List
			for(Menu menu : menuSet) {
				menus.add(menu);
			}
			
		}
		
		/*Comparator<Menu> comparator = new Comparator<Menu>() {
			public int compare(Menu m1, Menu m2) {
				Integer m1Order = m1.getMenuOrder();
				Integer m2Order = m2.getMenuOrder();
				if(m1Order != null && m2Order != null) {
					// 自定义排序
		            if (m1.getMenuOrder().intValue() != m2.getMenuOrder().intValue()) {
		                return m1.getMenuOrder().intValue() - m2.getMenuOrder().intValue();
		            } else {
		                // menuId排序
		                return Integer.parseInt(String.valueOf(m1.getMenuId().longValue() - m2.getMenuId().longValue()));
		            }
				} else {
					return 1;
				}
	        }
	    };*/
		Comparator<Menu> comparator = new Comparator<Menu>() {
            public int compare(Menu m1, Menu m2) {
                return Integer.parseInt(String.valueOf(m1.getMenuOrder().longValue() - m2.getMenuOrder().longValue()));
            }
        };
		Collections.sort(menus, comparator);
    	request.setAttribute("menuList", menus);
    	return  "admin/common/menu";
    }
    @ResponseBody
    @RequestMapping("/roleChange")
    public DataMessage roleChange(Long roleId) {
    	DataMessage dm = new DataMessage();
    	request.getSession().setAttribute("roleId", roleId);
    	dm.setResult(TownConstant.RESULT_CODE_SUCCESS);
    	return dm;
    }
    /**
     * 进入中心页面
     * @return index/index
     */
    @GetMapping("/index")
    public String gotoIndexPage() {
        return "admin/index/index";
    }

    /**
     * 进入修改个人信息页面
     * @return index/edit_self_info
     */
    @RequestMapping(value = "/gotoEditSelf", method = RequestMethod.GET)
    public String gotoEditSelfPage() {
    	Long userId = getUserId();//从session里面取登录用户id
    	User user = userService.queryById(userId);//根据用户id查询用户信息
        request.setAttribute("self", user);
        return "admin/index/edit_self_info";
    }

    /**
     * 修改管理员密码
     * @return index/edit_self_pswd
     */
    @RequestMapping(value = "/gotoEditPswd", method = RequestMethod.GET)
    public String gotoEditPswdPage() {
        return "admin/index/edit_self_pswd";
    }

    /**
     * 修改个人信息
     * @param realName 管理员姓名
     * @param telphone 手机号码
     * @param email 电子邮箱
     * @return DataMessage->Json
     */
    @ResponseBody
    @RequestMapping(value="/editSelf", method=RequestMethod.POST)
    public DataMessage editSelf(
    		@RequestParam(name="realName", required=true) String realName,
    		@RequestParam(name="telphone", required=true) String telphone,
    		@RequestParam(name="email", required=false) String email) {
        DataMessage dm = new DataMessage();
        // 后台验证
        if(!this.validateStringProperty(realName, 1, 50)) {
            dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("姓名不合法");
            return dm;
        }
        if(!this.validateStringProperty(telphone, 1, 50)) {
            dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("手机号码不合法");
            return dm;
        }
        this.userService.edit(getUserId(), null, null, null, null, null, realName, telphone, email, null, null, null, null, System.currentTimeMillis(),null);
        request.getSession().setAttribute(TownConstant.TOWN_SESSION_USER, this.userService.queryById(getUserId()));
        dm.setResult(TownConstant.RESULT_CODE_SUCCESS);
        dm.setMessage("个人信息编辑成功");
        return dm;
    }

    /**
     * 修改密码
     * @param oldPswd 原密码
     * @param newPswd 新密码
     * @return DataMessage->Json
     */
    @ResponseBody
    @RequestMapping(value="/editSeltPswd", method=RequestMethod.POST)
    public DataMessage editSelfPswd(
    			@RequestParam(name="oldPswd", required=true) String oldPswd,
    			@RequestParam(name="newPswd", required=true) String newPswd) {
        DataMessage dm = new DataMessage();
        // 后台验证
        if(!this.validateStringProperty(oldPswd, 1, 50)) {
            dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("愿密码不合法");
            return dm;
        }
        if(!this.validateStringProperty(newPswd, 1, 50)) {
            dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("新密码不合法");
            return dm;
        }
        User u = this.userService.queryLogin(1,getTelphone(), oldPswd);
        if(u == null) {
            dm.setResult(TownConstant.RESULT_CODE_DATA_ERROR);
            dm.setMessage("原密码不正确");
            return dm;
        } else {
            String cookieLoginToken = DataUtil.generateIdentificationCode(getUserId().toString());
            String loginToken = DataUtil.generateMD5(cookieLoginToken.getBytes());
            this.userService.edit(getUserId(), null, null, null, null, null, null, null, null, DataUtil.generateMD5(newPswd.getBytes()), loginToken, null, null, System.currentTimeMillis(),null);
        }
        dm.setResult(TownConstant.RESULT_CODE_SUCCESS);
        dm.setMessage("密码修改成功");
        return dm;
    }

    /**
     * 退出登录
     * @return login/login
     */
    @GetMapping("/logout")
    public String executeLogout() {
        Enumeration<String> em = request.getSession().getAttributeNames();
        while (em.hasMoreElements()) {
            request.getSession().removeAttribute(em.nextElement().toString());
        }
        return "redirect:/admin/login";
    }

    /**
     * 上传CKEditor中的图片资源
     */
    @ResponseBody
    @RequestMapping("/uploadCKEditor")
    public void uploadCKEditorResources(MultipartFile upload) throws IllegalStateException, IOException {
        String fileUrl = "";
        String resourcesUuid = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
        // 获取文件扩展名
        String extendsName = null;
        int dot = upload.getOriginalFilename().lastIndexOf('.');
        if ((dot >-1) && (dot < (upload.getOriginalFilename().length() - 1))) {
            extendsName = upload.getOriginalFilename().substring(dot);
        }
        String path = TownConstant.CDKEDITOR_IMAGE_PATH + resourcesUuid + extendsName;
        fileUrl = resourcesUuid + extendsName;
        File tempFile = new File(path);
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdir();
        }
        if (!tempFile.exists()) {
            tempFile.createNewFile();
        }
        upload.transferTo(tempFile);

        response.setCharacterEncoding("utf-8");
        String fullContentType = "text/html;charset=UTF-8";
        response.setHeader("X-Frame-Options", "SAMEORIGIN");
        response.setContentType(fullContentType);

        PrintWriter out = response.getWriter();
        String callback = request.getParameter("CKEditorFuncNum");
        String preUrl =request.getScheme()+"://"+request.getServerName()+":"+ request.getServerPort() + request.getContextPath() + "/cdkeditor/" + fileUrl;
        out.println("<script type=\"text/javascript\">");
        out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + preUrl + "','')");
        out.println("</script>");
    }
    
    
    @ResponseBody
    @RequestMapping("/uploadVideo")
    public void uploadCKEditorVideo(MultipartFile upload) throws IllegalStateException, IOException {
        String fileUrl = "";
        String resourcesUuid = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
        // 获取文件扩展名
        String extendsName = null;
        int dot = upload.getOriginalFilename().lastIndexOf('.');
        if ((dot >-1) && (dot < (upload.getOriginalFilename().length() - 1))) {
            extendsName = upload.getOriginalFilename().substring(dot);
        }
        String path = TownConstant.CDKEDITOR_IMAGE_PATH + resourcesUuid + extendsName;
        fileUrl = resourcesUuid + extendsName;
        File tempFile = new File(path);
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdir();
        }
        if (!tempFile.exists()) {
            tempFile.createNewFile();
        }
        upload.transferTo(tempFile);

        response.setCharacterEncoding("utf-8");
        String fullContentType = "text/html;charset=UTF-8";
        response.setHeader("X-Frame-Options", "SAMEORIGIN");
        response.setContentType(fullContentType);
        PrintWriter out = response.getWriter();
        String callback = request.getParameter("CKEditorFuncNum");
        String videoPath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/cdkeditor/Flvplayer.swf?vcastr_file=";
        String preUrl =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath() + "/cdkeditor/"+fileUrl;
        out.println("<script type=\"text/javascript\">");
        out.println("window.parent.CKEDITOR.tools.callFunction("+callback+",'"+videoPath+preUrl+"','')");
        out.println("</script>");
    }

    /**
     * 上传图片资源
     */
    @ResponseBody
    @RequestMapping(value = "/uploadPicture")
    public String uploadPicture(MultipartFile pictureFile) throws IllegalStateException, IOException {
        String fileUrl = "";
        String resourcesUuid = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
        // 获取文件扩展名
        String extendsName = null;
        int dot = pictureFile.getOriginalFilename().lastIndexOf('.');
        if ((dot >-1) && (dot < (pictureFile.getOriginalFilename().length() - 1))) {
            extendsName = pictureFile.getOriginalFilename().substring(dot);
        }
        String path = TownConstant.CDKEDITOR_IMAGE_PATH + resourcesUuid + extendsName;
        fileUrl = resourcesUuid + extendsName;
        File tempFile = new File(path);
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdir();
        }
        if (!tempFile.exists()) {
            tempFile.createNewFile();
        }
        pictureFile.transferTo(tempFile);
        String preUrl = request.getScheme()+"://"+request.getServerName()+":"+ request.getServerPort() + request.getContextPath() + "/cdkeditor/" + fileUrl;
        return "{\"picture\":\"" + resourcesUuid + extendsName + "\",\"preUrl\":\"" + preUrl + "\"}";
    }
    
	/**
	 * 查询当前用户角色
	 * @return
	 */
    @ResponseBody
    @PostMapping("/selectRole")
    public DataMessage selectRole() {
    	DataMessage dm = new DataMessage();
    	List<Role> roleList = this.roleService.queryRoleByUserId(getUserId());
    	dm.setResult(TownConstant.RESULT_CODE_SUCCESS);
    	dm.setData(roleList);    	
    	return dm;
    }
}
